package com.eelye.util.winui.manager;

import com.eelye.util.winui.window.Process;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

class ProcessManagerTest_UT {

    @Nested
    class launchProcess {

        @Test
        void 测试存在的程序() throws Exception {
            Process p = ProcessManager.launchProcess("C:\\Windows\\system32\\mstsc.exe");
            assertNotNull(p);

            p.terminate();
        }

        @Test
        void 测试不存在的程序() {
            assertThrows(Exception.class, () -> {
                ProcessManager.launchProcess("C:\\Windows\\system32\\mstsc.exe1");
            });
        }
    }

    @Nested
    class waitForProcessExit {

        @Test
        void 测试程序关闭后_能正常返回() throws Exception {
            // 用记事本测试不成功，不知道怎么回事。
            Process p = ProcessManager.launchProcess("C:\\Windows\\system32\\mstsc.exe");

            // 启动一个线程去关闭这个程序
            new Thread(() -> {
                try {
                    Thread.sleep(500);
                    ProcessManager.terminateProcess(p);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();

            int exitCode = ProcessManager.waitForProcessExit(p);
            assertEquals(0, exitCode);
        }
    }

    @Nested
    class getProcessHandle {

        @Test
        void 测试获取存在进程号_应该能获取到句柄() throws Exception {
            // 用记事本测试不成功，不知道怎么回事。
            Process p = ProcessManager.launchProcess("C:\\Windows\\system32\\mstsc.exe");
            int processId = p.getId();
            assertNotNull(ProcessManager.getProcessHandle(processId));

            p.terminate();
        }

        @Test
        void 测试获取不存在进程号_应该不能获取到句柄() throws Exception {
            assertNull(ProcessManager.getProcessHandle(9999999));
        }
    }
}